#include "stdafx.h"
#include "QuakeFunctions.h"

static const int HUNK_MAXSIZE = 1024 * 1024 * 2;
static int hunkLowMark = 0;

static unsigned char theHunk[HUNK_MAXSIZE];

namespace IdQuake
{
	int	Hunk_LowMark (void)
	{
		return hunkLowMark;
	}

	void *Hunk_AllocName (int size, const QS::String&)
	{
		void* retval;

		if (size <= 0)
		{
			throw std::invalid_argument("invalid size");
		}

		//check for out-of-hunk-memory
		if ((hunkLowMark + size) >= HUNK_MAXSIZE)
		{
			throw std::bad_alloc("Hunk_AllocName: out of memory");
		}
		
		retval = &theHunk[hunkLowMark];

		//set new hunk low mark
		hunkLowMark += size;

		return retval;
	}

	void Hunk_FreeToLowMark (int mark)
	{
		if ( (mark > hunkLowMark) || (mark < 0) )
		{
			throw std::range_error("Hunk_FreeToLowMark: argument out of range");
		}

		hunkLowMark = mark;
	}


	int LittleLong(int l)
	{
		return l;
	}

	float LittleFloat (float f)
	{
		return f;
	}

	short LittleShort(short l)
	{
		return l;
	}

	void Q_memcpy (void *dest, void *src, int count)
	{
		memcpy(dest, src, count);
	}

	void Sys_Error (const QS::String&, ...)
	{
		throw std::runtime_error("A fatal error was reported");
	}

	void *Cache_Check (cache_user_t *c)
	{
		return c->data;
	}

	void Cache_Free (cache_user_t*){}

	vec_t Length(vec3_t v)
	{
		int		i;
		float	length;
		
		length = 0;
		for (i=0 ; i< 3 ; i++)
			length += v[i]*v[i];
		length = sqrt (length);		// FIXME

		return length;
	}

	int Q_strncmp (char *s1, char *s2, int count)
	{
		while (1)
		{
			if (!count--)
				return 0;
			if (*s1 != *s2)
				return -1;              // strings not equal    
			if (!*s1)
				return 0;               // strings are equal
			s1++;
			s2++;
		}
		
		return -1;
	}
}